<template>
    <div class="task-detail">
        <div class="box">
            <h3>任务动态</h3>
            <div class="bd">
                <div class="props">
                    <div class="prop-group" style="flex: 1;">
                        <div style='margin-right: 12px;'>{{detail.sn}}</div> 
                        <div style='margin-right: 12px;'>{{detail.service_name}}{{detail.order_name}}（手机号：{{detail.service_mobile}}）</div>   
                        <div style='margin-right: 12px;'>{{detail.plan_amount}} 积分</div>  
                        <div style='margin-right: 12px; color: red;'>{{detail.is_urgent}}</div>
                        <!-- <div style='margin-right: 12px; color: red;'>{{detail.is_monitor}}</div> -->
                    </div>
                    <div class="prop-group">
                        <a-button @click="handle_download_all_files" type='primary' style='margin-right: 12px;'>下载所有附件</a-button>
                        <a-button v-if="detail && detail.status_id === 1" @click="handle_set_task_finish" type='primary'>任务完成</a-button>
                    </div>
                </div>
                <a-steps progress-dot :current="task_step_current">
                    <a-step title="任务待审核" />
                    <template v-if='detail && detail.status_id !== 3'>
                        <a-step title="任务进行中" />
                        <a-step title="任务已完成" />
                    </template>
                    <template v-else>
                        <a-step title="审核不通过" />
                    </template>
                </a-steps>
                <push-list 
                    :task='detail'
                    :push_list='push_list'
                />
                <upload-file-push :create_push='handle_create_file_push'/>
            </div>
        </div>

        <div class="box">
            <h3>任务日历</h3>
            <div class="bd">
                <div>任务执行时间：
                    <a-form style='display: inline-block;' :form='time_form'>
                        <a-form-item label="" style="margin-bottom: 0;">
                            <a-range-picker
                                v-show="time_edit_visible" 
                                v-decorator="[
                                    'time_range',
                                    { 
                                        initialValue: time_range,//[2020-11-19,2020-12-19]
                                        rules: [ { required: true, message: '请选择任务的时间范围' } ]
                                    }
                                ]"
                                :allowClear='false'
                            />
                            <span v-show="!time_edit_visible">{{detail.period_time || '暂无'}}</span>
                        </a-form-item>
                    </a-form>
                    
                    <template v-if="detail.status_id === 0">
                        <a-button v-show="!time_edit_visible" @click="time_edit_visible=true" style='margin-left: 12px;' type='primary'>修改</a-button>
                        <a-button v-show="time_edit_visible" @click="handle_edit_task_time_range" style='margin-left: 12px;' type='primary'>保存</a-button>
                        <a-button v-show="time_edit_visible" @click="handle_reduct_task_time_range" style='margin-left: 12px;' type='primary'>还原默认</a-button>
                    </template>
                </div>
                <div style="display: flex; align-items: center; position: absolute; padding-top: 25px;">
                    今天：<span style='display: inline-block; width:20px; height:10px; background-color: #1890ff;'></span>
                    &nbsp;&nbsp;&nbsp;&nbsp;点击选择：<span style='display: inline-block; width:20px; height:10px; background-color: #e6f7ff;'></span>
                    &nbsp;&nbsp;&nbsp;&nbsp;任务时间：<span style='display: inline-block; width:20px; height:10px; background-color: #bdaf00;'></span>
                    &nbsp;&nbsp;&nbsp;&nbsp;含有推送：<span style='display: inline-block; width:10px; height:10px; border-radius: 10px; background-color: #fa5151;'></span>
                </div>
                <task-calendar 
                    :detail="detail"
                    :cycle="cycle"
                    :selected_times="time_push_times"
                    :push_list="time_push_list"
                ></task-calendar>
            </div>
        </div>

        <div class="box">
            <h3>任务地址</h3>
            <div class="bd">
                <div v-if="detail.status_id === 0" style="margin-top: 12px;">
                    <a-button v-if="!address_edit" type='primary' @click="handle_toggle_edit_address">修改</a-button>
                    <a-button @click="handle_address_edit" v-if="address_edit" type='primary'>保存</a-button>
                    <a-button @click="handle_address_reset" v-if="address_edit" type='primary' style='margin-left: 12px;'>还原默认</a-button>
                </div>
                <div v-if="address_edit" style="margin-top: 12px;">
                    <a-button v-if="detail.type_id === 1" @click="address_edit_visible=true" style='border-radius: 0px; height: 26px; width: 60px; margin: 20px 0px;' type='primary'>圈选</a-button>
                    <a-button v-else-if="detail.type_id === 2" @click="address_edit_visible=true" style='border-radius: 0px; height: 26px; width: 60px; margin: 20px 0px;' type='primary'>划线</a-button>
                    <a-button v-else-if='detail.type_id === 3' @click="address_edit_visible=true" style='border-radius: 0px; height: 26px; width: 60px; margin: 20px 0px;' type='primary'>描点</a-button>
                </div>

                <a-form style='margin-top: 12px;' :form='address_edit_form'>
                    <a-form-item  
                        label="飞行地址:"
                        :label-col="{ span: 2 }"
                        :wrapper-col="{ span: 14 }"
                        >
                        <a-input v-if="address_edit" read-only placeholder="请输入飞行地址" v-decorator="[
                            'address'
                        ]"/>
                        <span v-else>{{address_edit_form_param.address}}<img @click="address_show=true" class="address-show" v-if="detail.lng_lat" src="./../../assets/images/site.svg" alt=""></span>
                    </a-form-item>

                    <template v-if="detail.type_id === 1">
                        <a-form-item 
                            label="预计面积:"
                            :label-col="{ span: 2 }"
                            :wrapper-col="{ span: 14 }"
                            >
                                <div style='display: flex;'>
                                    <a-input read-only v-if="address_edit" placeholder="请输入预计面积" v-decorator="[
                                        'area'
                                    ]"/>
                                    <span v-else>{{address_edit_form_param.area}}</span>
                                    <span style='flex-shrink:0; margin-left: 12px;'>平方公里</span>
                                </div>
                        </a-form-item>
                    </template>
                    <template v-if="detail.type_id === 2">
                        <!-- <a-form-item  
                            label="预计长度:"
                            :label-col="{ span: 2 }"
                            :wrapper-col="{ span: 14 }"
                            >
                            <div style='display: flex;'>
                                <a-input readOnly v-if="address_edit" placeholder="请输入预计长度" v-decorator="[
                                    'length'
                                ]"/>
                                <span v-else>{{address_edit_form_param.length || 0}}</span>
                                <span style='flex-shrink:0; margin-left: 12px;'>公里</span>
                            </div>
                        </a-form-item> -->
                        <!-- <a-form-item
                            label="河道宽度:"
                            :label-col="{ span: 2 }"
                            :wrapper-col="{ span: 14 }"
                            >
                            <a-select @change='handle_change_river_width' v-if="address_edit" placeholder="请选择河道宽度" v-decorator="[
                                'river_width_index',
                            ]">
                                <a-select-option v-for="(width, index) in address_river_width_list" :key="index" :value="String(index)">
                                    <span v-if="width.min === 0">{{width.max}}米以内</span>
                                    <span v-else-if="width.max === 0">{{width.min}}米以上</span>
                                    <span v-else>{{width.min}}米-{{width.max}}米</span>
                                </a-select-option>
                            </a-select>
                            <span v-else>{{address_edit_form_param.river_width}}米</span>
                        </a-form-item> -->
                        <a-form-item 
                            label="预计面积:"
                            :label-col="{ span: 2 }"
                            :wrapper-col="{ span: 14 }"
                            >
                            <div style='display: flex;'>
                                <span>{{address_edit_form_param.area}}</span>
                                <span style='flex-shrink:0; margin-left: 12px;'>平方公里</span>
                            </div>
                        </a-form-item>
                    </template>
                    <template v-if="detail.type_id === 3">
                        <a-form-item 
                            label="巡检点数:"
                            :label-col="{ span: 2 }"
                            :wrapper-col="{ span: 14 }"
                            >
                            <a-input read-only v-if="address_edit" placeholder="请输入巡检点数" v-decorator="[
                                'area'
                            ]"/>
                            <div v-else style='display: flex;'>
                                <span>{{address_edit_form_param.area}}</span>
                                <span style='flex-shrink:0; margin-left: 12px;'>个</span>
                            </div>
                        </a-form-item>
                    </template>
                </a-form>
            </div>
        </div>

        <div class="box">
            <h3>飞手信息</h3>
            <div class="bd">
                <select-pilot 
                    :pilot_task='detail'
                    :pilot_list='pilot_list'
                    :pilot_pagination='pilot_pagination'
                ></select-pilot>
            </div>
        </div>

        <a-modal
            v-model="address_edit_visible"
            title="飞行地址" 
            :footer="null"
            centered
            width="800"
            :keyboard = 'false'
            :maskClosable = 'false'
            >
            <amap-x 
                id="edit"
                :type='detail.type_id' 
                :lng_lats='detail.lng_lat'
                :edit='true'
                :address="address_edit_form_param.address"
                :update_address="update_address"
                >
            </amap-x>
        </a-modal>

        <a-modal
            v-model="address_show"
            title="飞行地址" 
            :footer="null"
            centered
            width="800"
            :keyboard = 'false'
            :maskClosable = 'false'
            >
            <amap-x
                id="search"
                :type='detail.type_id'
                :lng_lats='detail.lng_lat'
                :address="address_edit_form_param.address"
                :update_address="update_address"
            ></amap-x>
        </a-modal>
    </div>
</template>

<script>
    import moment from 'moment'
    import PushList from './push-list'
    import UploadFilePush from './upload-file-push'
    import TaskCalendar from './task-calendar'
    import SelectPilot from './select-pilot'
    import AmapX from './map'
    import axios from 'axios';
    export default {
        name: 'task-detail',
        components: { PushList, UploadFilePush, TaskCalendar, SelectPilot, AmapX },
        data(){
            return {
                detail: {
                    status_id: 0,
                    address: ''
                },
                task_step_current: 0,

                push_list_show_all: true,
                push_list: [],
                push_list_pagination: {
                    page: 1,
                    page_size: 3
                },

                time_form: this.$form.createForm(this),
                time_edit_visible: false,
                time_push_times: [],
                time_push_list: [],

                pilot_list: [],
                pilot_pagination: {
                    total: 0,
                    current: 1,
                    pageSize: 10,
                    showQuickJumper: true,
                    onChange: (page, size) => {
                        //列表展示条数改变
                        this.handle_change_pilot_pagination(page, size)
                    },
                },

                address_edit: false,
                address_edit_visible: false,
                unit_map: {
                    '3': '平方公里',
                    '4': '个',
                    '5': '公里',
                },
                address_edit_form: this.$form.createForm(this),
                address_edit_form_param: {
                    address: undefined,
                    area: '0',
                    length: '',
                    river_width: null,
                    river_width_index: null,
                    lng_lat: ''
                },

                address_river_width_list: [
                    { min: 0, max: 100, value: 100 },
                    { min: 100, max: 400, value: 400  },
                    { min: 400, max: 700, value: 700  },
                    { min: 700, max: 1000, value: 1000  },
                    { min: 1000, max: 1300, value: 1300  },
                    { min: 1300, max: 1600, value: 1600  },
                    { min: 1600, max: 1900, value: 1900  },
                    { min: 1900, max: 2100, value: 2100  },
                    { min: 2100, max: 0, value: 2100  }
                ],
                address_river_width_map: {
                    0: '100米以内',
                    1: '100米-400米',
                    2: '400米-700米',
                    3: '700米-1000米',
                    4: '1000米-1300米',
                    5: '1300米-1600米',
                    6: '1600米-1900米',
                    7: '1900米-2100米',
                    8: '2100米以上',
                },
                address_show: false
            }
        },
        computed: {
            cycle(){
                const { detail } = this
                if(detail){
                    return (detail && detail.period_time) ? detail.period_time.split('~') : []
                }
                return []
            },
            time_range(){
                const { detail } = this
                if(detail){
                    let cycle = detail.period_time,
                        cycle_splits = cycle ? cycle.split('~') : []
                    if(cycle_splits.length){
                        return [moment(cycle_splits[0], 'YYYY/MM/DD'), moment(cycle_splits[1], 'YYYY/MM/DD')]
                    }
                }
                return []
            },
            get_unit() {
                let { detail, unit_map } = this
                return unit_map[detail.type_id] || ''
            },
            get_area(){
                return 0
            }
        },
        methods: {
            async get_detail(){
                let data = await this.http('get', 'task/view', {
                    id: this.$route.params.id
                });
                // data.type_id = 3
                let detail = this.detail = data || {}
                this.detail.area = Number(this.detail.area)
                this.init_task_step()
                this.init_address_params()
            },

            /** 下载所有附件 */
            async handle_download_all_files(){
                let res = await this.http('get', `push/files-count?task_id=${this.detail.id}`);
                if(res && res.status){
                    if(res.count > 0){
                        let a = document.createElement('a')
                        a.href = `${process.env.VUE_APP_BASE_URL}push/files?task_id=${this.detail.id}`
                        a.target = '_blank'
                        let body = document.getElementsByTagName('body')[0]
                        body.appendChild(a)
                        a.click()
                    }else{
                        this.$message.success('附件总数为0', 1)
                    }
                }else{
                    this.$message.success('查询附件总数失败', 1)
                }
            },
            /** 设置任务成功 */
            handle_set_task_finish(){
                this.$confirm({
                    title: '系统提示',
                    content: '确定要将该任务状态改为成功么？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: close => {
                        this.http('get', `task/complete?id=${this.detail.id}`).then(res => {
                            this.$message.success(res.msg, 1)
                            this.get_detail()
                        }).catch(e => {
                            this.$message.success(e.message, 1)
                        }).finally(() => close())
                    }
                });
            },
            /** 设置任务状态 */
            init_task_step(){
                const { detail } = this
                if(detail){
                    let status_id = detail.status_id || 0
                    this.task_step_current = (status_id == 3?1:status_id)
                }
            },
            /** 获取推送列表
             * 1、首先只获取三条数据，然后显示 `展开所有动态` 按钮，点击该按钮后，显示所有动态
             */
            get_push_list(){
                const { detail } = this
                if(detail && detail.id){
                    this.http('get', 'push/index', {
                        task_id: detail.id,
                        order_id: detail.order_id,
                        ...this.push_list_pagination
                    }).then(res => {
                        res.data = res.data.map(item => ({
                            ...item,
                            isDel: moment().diff(moment(item.updated_at), 'minutes') < 30
                        }))
                        this.push_list = res.data || []
                    })
                }
                
            },
            /** 获取所有的推送列表 */
            async get_all_push_list(){
                this.push_list_pagination.page = 1
                this.push_list_pagination.page_size = 10000
                await this.get_push_list()
            },
            /** 拒绝任务 */
            async refuse_task(push, values){
                let resp = await this.http('put', `/push/upgrade?id=${push.id}`, {
                    status: 1, 
                    handle: 0,
                    ...values
                })
                if(resp && resp.status === 200){
                    this.$message.success('拒绝任务成功', 1);
                    await this.get_push_list()
                    await this.get_detail()
                }else{
                    this.$message.success('拒绝任务失败', 1);
                }
            },
            /** 接受任务 */
            async accept_task(push){
                let resp = await this.http('put', `/push/upgrade?id=${push.id}`, {
                    status: 1, 
                    handle: 1,
                })
                if(resp && resp.status === 200){
                    this.$message.success('接受任务成功', 1);
                    await this.get_push_list()
                    await this.get_detail()
                }else{
                    this.$message.success('接受任务失败', 1);
                }
            },
            /** 修改文件推送 */
            async push_file_edit(push, values){
                let resp = await this.http('put', `/push/upgrade?id=${push.id}`, {
                    ...values
                })
                if(resp && resp.status === 200){
                    this.$message.success('修改成功', 1);
                    await this.get_push_list()
                }else{
                    this.$message.error('修改失败', 1);
                }
            },
            /** 删除文件推送 */
            push_file_delete(push){
                this.$confirm({
                    title: '系统提示',
                    content: '确定要删除该消息么',
                    okType: 'danger',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: async close => {
                        let resp = await this.http('delete', `/push/delete?id=${push.id}`)
                        if(resp && resp.status === 'success'){
                            this.$message.success('删除成功', 1);
                            await this.get_push_list()
                            close()
                        }else{
                            this.$message.error('删除失败', 1);
                        }
                    }
                });
            },
            /** 创建文件推送 */
            async handle_create_file_push(data){
                let { detail } = this

                let res = await this.http('post', '/push/add', {
                    task_id: detail.id,
                    ...data
                })

                if(res.status === 200){
                    await this.get_push_list()
                    this.$message.success(res.msg, 1)
                    return true
                }else{
                    this.$message.error(res.msg, 1);
                    return false
                }
            },
            /** 修改任务时间 */
            handle_edit_task_time_range(){
                this.time_form.validateFields(async (err, values) => {
                    if(!err){
                        let times = values.time_range,
                            start_time = times[0].format('YYYY-MM-DD')+' 00:00',
                            end_time = times[1].format('YYYY-MM-DD')+' 23:59'

                        let res = await this.http('put', `/task/update?id=${this.detail.id}`, {
                            plan_time: [start_time, end_time]
                        })
                
                        if(res && res.status === 200){
                            this.$message.success('修改成功', 1);
                            await this.get_detail()
                            this.time_edit_visible = false
                        }else{
                            this.$message.error('修改失败', 1);
                        }
                    }
                })
            },
            /** 重置任务时间 */
            handle_reduct_task_time_range(){
                this.time_form.setFieldsValue({
                    time_range: this.time_range
                })
            },

            /** 获取推送的文件的创建的时间列表 */
            get_all_push_time(){
                const { detail } = this
                if(detail){
                    this.http('get', 'push/index', {
                        task_id: detail.id,
                        order_id: detail.order_id,
                        page: 1,
                        page_size: 10000,
                    }).then(res => {
                        this.time_push_times = res.data.map(item => {
                            return item.created_at ? item.created_at.split(' ')[0] : undefined
                        })
                    })
                }
            },
            /** 根据时间获取对应的推送列表 */
            get_push_by_time(e){
                let time = moment().format('YYYY-MM-DD')
                if(e){
                    time = e.format('YYYY-MM-DD')
                }
                const { detail } = this
                if(detail){
                    this.http('get', 'push/index', {
                        task_id: detail.id,
                        order_id: detail.order_id,
                        page: 1, 
                        page_size: 10000,
                        created_at: time
                    }).then(res => {
                        this.time_push_list = res.data || []
                    })
                }
            },

            /** 初始化地址参数 */
            init_address_params(){
                let { address, type_id, area, length, river_width, river_width_index, lng_lat} = this.detail
                console.log("area--->",area);
                this.address_edit_form_param.address = address
                this.address_edit_form_param.area = area < 1 ? 1 : area.toFixed(0)
                this.address_edit_form_param.length = length
                this.address_edit_form_param.river_width = river_width || '0'
                this.address_edit_form_param.river_width_index = river_width_index
                this.address_edit_form_param.lng_lat = lng_lat
            },

            /** 切换地址的修改状态 */
            handle_toggle_edit_address(){
                this.address_edit = true
                const { address_edit_form, address_edit_form_param } = this
                this.$nextTick(() => {
                    address_edit_form.setFieldsValue(address_edit_form_param)
                })
            },
            /** 修改河道宽度下拉框 */
            handle_change_river_width(e){
                console.log(e)
                let { address_river_width_list, address_edit_form_param } = this,
                    { length } = address_edit_form_param,
                    river_width = (address_river_width_list[e] && address_river_width_list[e].value) || 0

                address_edit_form_param.area = river_width*length
                address_edit_form_param.river_width = river_width
            },
            /** 地址回调 */
            update_address(options){
                console.log(' --> options: ', options)
                let { address, area, lng_lat } = options,
                    { address_edit_form_param } = this,
                    { type_id } = this.detail

                if(type_id === 1){
                    address_edit_form_param.address = address
                    address_edit_form_param.area = area
                    address_edit_form_param.lng_lat = JSON.stringify(lng_lat)
                }else if(type_id === 2){
                    const { river_width_index } = address_edit_form_param,
                        { address_river_width_list } = this
                    
                    let length = area,
                        _river_width = address_river_width_list[river_width_index] ? address_river_width_list[river_width_index].value : 0,
                        _area = length*_river_width/1000

                    address_edit_form_param.address = address
                    address_edit_form_param.length = length
                    address_edit_form_param.area = _area
                    address_edit_form_param.river_width = _river_width
                    address_edit_form_param.lng_lat = JSON.stringify(lng_lat)
                }else if(type_id === 3){
                    address_edit_form_param.address = address
                    address_edit_form_param.area = area
                    address_edit_form_param.lng_lat = JSON.stringify(lng_lat)
                }

                this.$nextTick(() => {
                    this.address_edit_form.setFieldsValue(address_edit_form_param)
                })
                this.address_edit_visible = false
            },
            /** 修改地址 */
            async handle_address_edit(){
                console.log('address_edit_form:', this.address_edit_form_param)
                this.address_edit_form.validateFields(async (err, values) => {
                    if(!err){

                        this.address_edit_form_param.length += ''
                        this.address_edit_form_param.river_width += ''

                        let res = await this.http('put', `orders/update?id=${this.detail.order_id}`, this.address_edit_form_param)
                        if(res && res.status === 200){
                            this.$message.success('修改成功', 1);
                            this.$router.go(0)
                            // this.get_detail();
                            // this.address_edit = false;
                        }else{
                            this.$message.error('修改失败', 1);
                        }
                    }
                })
            },
            /** 重置地址数据 */
            handle_address_reset(){
                const { address_edit_form_param, detail } = this
                
                Object.keys(address_edit_form_param).forEach(key => {
                    address_edit_form_param[key] = detail[key]
                })

                this.$nextTick(() => {
                    this.address_edit_form.setFieldsValue(address_edit_form_param)
                })
            },

            /** 获取与此任务关联的飞手 */
            get_pilots_by_task(pagination){
                const { detail, pilot_pagination } = this
                this.http('get', 'pilot/index', {
                    task_id: detail.id,
                    page: pilot_pagination.current,
                    page_size: pilot_pagination.pageSize
                }).then(res => {
                    this.pilot_list = res.data || []
                    console.log("this.pilot_list---->",this.pilot_list)
                    this.pilot_pagination.total = res.total_count || 0
                })
            },
            async handle_change_pilot_pagination(page, page_size){
                this.pilot_pagination.current = page
                this.pilot_pagination.pageSize = page_size
                await this.get_pilots_by_task()
            },

            edit_pilot(pilots){
                const { detail } = this
                if(detail){
                    this.http('put', 'pilot/update?id=' + detail.id, {
                        pilots
                    }).then(async res => {
                        if (res.code == 200) {
                            this.$message.success(res.msg, 1);
                            await this.get_pilots_by_task({
                                page: 1,
                                page_size: 10
                            })
                        } else {
                            this.$message.error(res.msg, 1);
                        }
                    })
                }

            },
        },
        async mounted(){
            await this.get_detail()
            await this.get_push_list()
            await this.get_all_push_time()
            await this.get_push_by_time()
            await this.get_pilots_by_task()
        }
    }
</script>

<style lang="scss" scoped>
    .task-detail{
        .props{
            display: flex;
            justify-content: space-between;
            height: 50px;
            .prop-group{
                display: flex;
                align-items: center;
            }
        }
        .box{
            margin-bottom: 20px;
            .bd{
                padding: 0px 20px;
            }
        }
    }
</style>